export function getDayStartTime(day) {
    return new Date(day.getFullYear(), day.getMonth(), day.getDate(), 0, 0, 0);
}

export function getDayEndTime(day) {
    return new Date(day.getFullYear(), day.getMonth(), day.getDate(), 23, 59, 59);
}

export function getToDayStartTime() {
    return getDayStartTime(new Date())
}

export function getToDayEndTime() {
    return getDayEndTime(new Date())
}

export function getLastWeekTime() {
    const toDayTime = getToDayStartTime();
    toDayTime.setTime(toDayTime.getTime() - 7 * 24 * 3600 * 1000);
    return toDayTime;
}

export function getLastMonthTime() {
    const toDayTime = getToDayStartTime();
    toDayTime.setTime(toDayTime.getTime() - 30 * 24 * 3600 * 1000);
    return toDayTime;
}

export function getLastYearTime() {
    const toDayTime = getToDayStartTime();
    toDayTime.setTime(toDayTime.getTime() - 365 * 24 * 3600 * 1000);
    return toDayTime;
}
export function getToday() {
    return getFormatDateStr(getToDayStartTime());
}

export function getLastDay() {
    const toDayTime = getToDayStartTime();
    toDayTime.setTime(toDayTime.getTime() - 24 * 3600 * 1000);
    return getFormatDateStr(toDayTime);
}

export function getLastWeekDay() {
    return getFormatDateStr(getLastWeekTime());
}

export function getFormatDateStr(dayTime) {
    const year = dayTime.getFullYear();
    const month = String(dayTime.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1并补零
    const day = String(dayTime.getDate()).padStart(2, '0'); // 日期补零
    return `${year}-${month}-${day}`;
}

export function formatStandardTime(date) {
    // 处理输入类型：支持 Date对象/时间戳/日期字符串
    const d = date instanceof Date ? date : new Date(date);

    // 校验日期合法性
    if (isNaN(d.getTime())) return null;

    // 提取时间部件并补零
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');

    // 拼接目标格式
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 计算时间差函数
export function getMinutesDifference(startTime, endTime) {
    try {
        // 1. 将字符串转换为 Date 对象（自动处理时区）
        const targetDate1 = new Date(startTime);
        let targetDate2;
        if (endTime) {
            targetDate2 = new Date(endTime)
        } else {
            targetDate2 = new Date();
        }
        // 2. 获取当前时间

        // 3. 计算时间差（毫秒）
        const diffMs = targetDate2 - targetDate1

        // 4. 转换为分钟并取整
        return Math.floor(diffMs / (1000 * 60));
    } catch (error) {
        console.error('时间格式错误:', error);
        return null;
    }
}
